<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{number}} - {{title}}</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/codemirror.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/theme/monokai.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/addon/hint/show-hint.min.css" rel="stylesheet">
    <style>
        .CodeMirror {
            height: 400px;
            border: 1px solid #ddd;
        }

        .question-content {
            white-space: pre-wrap;
            background-color: #f8f9fa;
            padding: 1rem;
            border-radius: 0.25rem;
        }

        .result-container {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #e9ecef;
        }

        .result-header {
            display: flex;
            gap: 20px;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e9ecef;
        }

        .result-header span {
            color: #495057;
            font-size: 14px;
        }

        .result-content {
            min-height: 100px;
        }

        .output {
            white-space: pre-wrap;
            font-family: monospace;
            color: #212529;
            line-height: 1.5;
        }

        .error {
            background: #fff5f5;
            border-left: 4px solid #ff6b6b;
            padding: 10px 15px;
            margin-top: 10px;
        }

        .error h4 {
            color: #c92a2a;
            margin: 0 0 5px 0;
        }

        .error pre {
            color: #c92a2a;
            margin: 0;
            white-space: pre-wrap;
        }

        .btn-submit {
            background: #4dabf7;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }

        .btn-submit:hover {
            background: #339af0;
        }

        .btn-submit:disabled {
            background: #adb5bd;
            cursor: not-allowed;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/">在线评测系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="/all_questions">题目列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/user/submissions">我的提交</a>
                    </li>
                </ul>
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" id="logoutLink" href="/logout" style="display: none;">退出</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="loginLink" href="/login">登录</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="question-title">{{number}}. {{title}} <span class="badge bg-{{star_color}} question-star">{{star}}</span></h2>
                    <div>
                        <a href="/forum/{{number}}" class="btn btn-outline-primary me-2">
                            <i class="bi bi-chat-dots"></i> 讨论区
                        </a>
                    </div>
                </div>

                <!-- 隐藏的数据字段 -->
                <div style="display: none;">
                    <span name="cpu_limit">{{cpu_limit}}</span>
                    <span name="mem_limit">{{mem_limit}}</span>
                    <div name="test_input">{{test_input}}</div>
                    <div name="test_output">{{test_output}}</div>
                </div>

                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">题目描述</h5>
                        <div class="question-content question-desc">{{desc}}</div>
                        
                        <h5 class="card-title mt-4">限制条件</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <p>CPU限制: <span class="cpu-limit">{{cpu_limit}}</span> ms</p>
                            </div>
                            <div class="col-md-6">
                                <p>内存限制: <span class="mem-limit">{{mem_limit}}</span> MB</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="code-section">
                    <div class="code-header">
                        <h3 style="margin-bottom: 15px; color: #2c3e50;">代码编辑</h3>
                        <div class="language-selector">
                            <label for="language">编程语言：</label>
                            <select id="language" class="form-select" style="width: 150px;">
                                <option value="cpp">C++</option>
                                <option value="python">Python</option>
                                <option value="go">Golang</option>
                                <option value="c">C</option>
                            </select>
                        </div>
                    </div>
                    <div class="code-editor">
                        <textarea id="codeEditor"></textarea>
                    </div>
                </div>
                <!-- 提交并且得到结果，并显示 -->
                <div class="result-section">
                    <h3 style="margin-bottom: 15px; color: #2c3e50;">运行结果</h3>
                    <div class="result-container">
                        <div class="result-header">
                            <span class="status">状态：<span id="status">等待提交</span></span>
                            <span class="time"> <span id="time">-</span> </span>
                            <span class="memory"> <span id="memory">-</span> </span>
                        </div>
                        <div class="result-content">
                            <div id="output" class="output">
                                <p style="color: #666; font-style: italic;">提交代码后，编译运行结果将显示在这里</p>
                            </div>
                            <div id="error" class="error" style="display: none;">
                                <h4>错误信息</h4>
                                <pre id="error-message"></pre>
                            </div>
                        </div>
                    </div>
                    <button class="btn-submit" onclick="submit()" id="submit-btn">提交代码</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/clike/clike.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/python/python.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/go/go.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/addon/hint/show-hint.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/addon/hint/anyword-hint.min.js"></script>
    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById("codeEditor"), {
            mode: "text/x-c++src",
            theme: "monokai",
            lineNumbers: true,
            indentUnit: 4,
            autoCloseBrackets: true,
            matchBrackets: true,
            extraKeys: {
                "Ctrl-Space": "autocomplete",  // 启用代码补全快捷键
                "Tab": function (cm) {          // 改进Tab键处理
                    if (cm.somethingSelected()) {
                        cm.indentSelection("add");
                    } else {
                        cm.replaceSelection(cm.getOption("indentWithTabs") ? "\t" :
                            Array(cm.getOption("indentUnit") + 1).join(" "), "end", "+input");
                    }
                }
            },
            hintOptions: {  // 代码补全配置
                hint: CodeMirror.hint.anyword,
                completeSingle: false
            }
        });
        document.getElementById('language').addEventListener('change', function () {
            const modeMap = {
                'python': 'python',
                'go': 'go',
                'c': 'text/x-csrc',
                'cpp': 'text/x-c++src'
            };
            editor.setOption('mode', modeMap[this.value] || 'text/x-c++src');
        });

        function checkLogin() {
            const loginLink = document.getElementById('loginLink');
            const logoutLink = document.getElementById('logoutLink');

            // 检查Cookie中是否有user_id
            const cookies = document.cookie.split(';');
            let isLoggedIn = false;

            for (let cookie of cookies) {
                cookie = cookie.trim();
                if (cookie.startsWith('user_id=')) {
                    isLoggedIn = true;
                    break;
                }
            }

            // 根据登录状态切换显示
            if (isLoggedIn) {
                loginLink.style.display = 'none';
                logoutLink.style.display = 'inline-block';
            } else {
                loginLink.style.display = 'inline-block';
                logoutLink.style.display = 'none';
            }
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', checkLogin);

        // 定期检查登录状态（每5秒）
        setInterval(checkLogin, 5000);

        function submit() {
            const code = editor.getValue();
            const language = document.getElementById('language').value;

            // 显示加载状态
            document.getElementById('status').textContent = '正在编译运行...';
            document.getElementById('output').innerHTML = '<p style="color: #666; font-style: italic;">正在编译运行，请稍候...</p>';
            document.getElementById('error').style.display = 'none';

            // 发送请求
            fetch('/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    code: code,
                    language: language,
                    number: '{{number}}'
                })
            })
                .then(response => response.json())
                .then(data => {
                    // 调试信息：显示接收到的原始数据
                    console.log('收到后端返回的数据:', data);
                    
                    // 更新状态
                    let displayStatus = '';
                    let statusColor = '';
                    
                    // 确保result_code是数字
                    const resultCode = Number(data.result_code);
                    console.log('状态码:', resultCode, '类型:', typeof resultCode);
                    
                    // 根据result_code值判断状态
                    if (resultCode === 0) {
                        console.log('状态判断: 通过');
                        displayStatus = '通过';
                        statusColor = '#2ecc71';
                    } else if (resultCode === 1) {
                        console.log('状态判断: 未通过');
                        displayStatus = '未通过';
                        statusColor = '#e74c3c';
                    } else if (resultCode === -1) {
                        console.log('状态判断: 空代码');
                        displayStatus = '空代码';
                        statusColor = '#e74c3c';
                    } else if (resultCode === -2) {
                        console.log('状态判断: 内部错误');
                        displayStatus = '内部错误';
                        statusColor = '#e74c3c';
                    } else if (resultCode === -3) {
                        console.log('状态判断: 编译错误');
                        displayStatus = '编译错误';
                        statusColor = '#e74c3c';
                    } else if (resultCode === 6 || resultCode === 134) { // SIGABRT
                        console.log('状态判断: 内存超出 (SIGABRT)');
                        displayStatus = '内存超出';
                        statusColor = '#e74c3c';
                    } else if (resultCode === 24 || resultCode === 152) { // SIGXCPU
                        console.log('状态判断: 运行超时 (SIGXCPU)');
                        displayStatus = '运行超时';
                        statusColor = '#e74c3c';
                    } else if (resultCode === 8 || resultCode === 136) { // SIGFPE
                        console.log('状态判断: 浮点错误 (SIGFPE)');
                        displayStatus = '浮点错误';
                        statusColor = '#e74c3c';
                    } else if (resultCode === 11 || resultCode === 139) { // SIGSEGV
                        console.log('状态判断: 段错误 (SIGSEGV)');
                        displayStatus = '段错误';
                        statusColor = '#e74c3c';
                    } else {
                        console.log('状态判断: 运行错误，未知状态码:', resultCode);
                        displayStatus = '运行错误';
                        statusColor = '#e74c3c';
                    }
                    
                    console.log('最终状态显示:', displayStatus);
                    console.log('状态颜色:', statusColor);
                    
                    document.getElementById('status').textContent = displayStatus;
                    document.getElementById('status').style.color = statusColor;

                    // 更新时间和内存信息
                    console.log('运行时间:', data.time);
                    console.log('内存使用:', data.memory);
                    document.getElementById('time').textContent = data.time || '-';
                    document.getElementById('memory').textContent = data.memory || '-';

                    // 显示输出
                    let outputHtml = '';
                    if (data.output) {
                        console.log('程序输出:', data.output);
                        outputHtml += '<pre>' + data.output + '</pre>';
                    }

                    // 显示测试结果
                    if (data.pass_rate !== undefined && data.pass_rate < 100) {
                        console.log('通过率:', data.pass_rate + '%');
                        outputHtml += '<div style="background-color: #f8d7da; padding: 15px; border-radius: 4px; margin-top: 10px;">';
                        outputHtml += '<p style="color: #721c24; margin: 0;">测试未通过，通过率: ' + data.pass_rate + '%</p>';
                        
                        if (data.error_case) {
                            console.log('错误用例:', data.error_case);
                            outputHtml += '<div style="margin-top: 10px;">';
                            const lines = data.error_case.split('\n');
                            let currentSection = '';
                            let caseNumber = 1;
                            
                            outputHtml += '<p style="margin: 5px 0;">错误用例：</p>';
                            outputHtml += '<p style="margin: 5px 0;">测试用例 ' + caseNumber + ':</p>';
                            
                            for (const line of lines) {
                                if (line.startsWith('输入:')) {
                                    outputHtml += '<p style="margin: 5px 0;">输入：</p>';
                                    continue;
                                } else if (line.startsWith('期望输出:')) {
                                    outputHtml += '<p style="margin: 5px 0;">期望输出：</p>';
                                    continue;
                                } else if (line.startsWith('实际输出:')) {
                                    outputHtml += '<p style="margin: 5px 0;">实际输出：</p>';
                                    continue;
                                }
                                
                                if (line.trim() && !line.startsWith('测试用例')) {
                                    outputHtml += '<pre style="margin: 0 0 10px 0;">' + line + '</pre>';
                                }
                            }
                            outputHtml += '</div>';
                        }
                        outputHtml += '</div>';
                    } else if (data.pass_rate === 100) {
                        console.log('测试完全通过');
                        outputHtml += '<div style="background-color: #d4edda; padding: 15px; border-radius: 4px; margin-top: 10px;">';
                        outputHtml += '<p style="color: #155724; margin: 0;">测试通过，通过率: 100%</p>';
                        outputHtml += '</div>';
                    }

                    // 显示错误信息
                    if (data.error) {
                        console.log('错误信息:', data.error);
                        outputHtml += '<div class="error" style="display: block;">';
                        outputHtml += '<h4>错误信息</h4>';
                        outputHtml += '<pre>' + data.error + '</pre>';
                        outputHtml += '</div>';
                    }

                    console.log('最终HTML输出:', outputHtml);
                    document.getElementById('output').innerHTML = outputHtml;
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('status').textContent = '提交失败';
                    document.getElementById('status').style.color = '#e74c3c';
                    document.getElementById('output').innerHTML = '<p style="color: #e74c3c;">提交失败，请重试</p>';
                });
        }
    </script>
</body>

</html>